<template>
  <el-card class="mt-10">
    <el-form
      ref="skuFormRef"
      :model="skuFormData"
      :rules="skuFormRules"
      class="addSkuForm"
    >
      <el-form-item label="SPU名称">{{ spuStore.spuName }} </el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input placeholder="SKU名称" v-model="skuFormData.skuName" />
      </el-form-item>
      <el-form-item label="价格(元)" prop="price">
        <el-input-number
          :min="0"
          :max="100000000"
          class="sku-input-number"
          controls-position="right"
          placeholder="0"
          v-model="skuFormData.price"
        />
      </el-form-item>
      <el-form-item label="重量(千克)" prop="weight">
        <el-input-number
          v-model="skuFormData.weight"
          :min="0"
          :max="100000000"
          class="sku-input-number"
          controls-position="right"
          placeholder="0"
        />
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          type="textarea"
          placeholder="规格描述"
          v-model="skuFormData.skuDesc"
        />
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row :gutter="10" class="skuRow">
          <el-col
            :xs="8"
            :sm="6"
            :md="4"
            :lg="3"
            :xl="1"
            v-for="(platformAttr, index) in platformAttrList"
            :key="platformAttr.id"
          >
            <div class="sku-select-wrap">
              <span>{{ platformAttr.attrName }}</span>
              <el-select
                class="sku-select"
                v-model="skuFormData.skuAttrValueList[index]"
              >
                <el-option
                  v-for="attrValue in platformAttr.attrValueList"
                  :key="attrValue.id"
                  :label="attrValue.valueName"
                  :value="`${platformAttr.id}:${platformAttr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row :gutter="10" class="skuRow">
          <el-col
            :xs="8"
            :sm="6"
            :md="4"
            :lg="3"
            :xl="1"
            v-for="(saleAttr, index) in saleAttrList"
            :key="saleAttr.id"
          >
            <div class="sku-select-wrap">
              <span :style="{ width: '100px', 'text-align': 'right' }">{{
                saleAttr.saleAttrName
              }}</span>
              <el-select
                class="sku-select"
                v-model="skuFormData.skuSaleAttrValueList[index]"
              >
                <el-option
                  v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                  :key="saleAttrValue.baseSaleAttrId"
                  :label="saleAttrValue.saleAttrValueName"
                  :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.baseSaleAttrId}:${saleAttrValue.saleAttrValueName}`"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table border :data="imageList" @selection-change="selectionChange">
          <el-table-column type="selection" width="60" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img
                :src="row.imgUrl"
                :style="{ width: '120px', height: '120px' }"
              />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-tag type="success" v-if="row.isDefault === '1'">默认</el-tag>
              <el-button
                type="primary"
                size="small"
                v-else
                @click="setDefault(row)"
                >设置默认</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-button type="primary" @click="confirmAddSku">确定</el-button>
      <el-button @click="setIsShow">取消</el-button>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "LAddSku",
};
</script>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { useSpuStore } from "@/stores/spu";
import type { AttrList } from "@/api/product/model/attrmodel";
import type { SpuSaleAttrList } from "@/api/product/model/spuModel";
import type {
  SkuImageList,
  SkuImageItem,
  SkuCommon,
} from "@/api/product/model/skuModel";
import { getSaveSkuInfoApi } from "@/api/product/sku";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { getAttrListApi } from "@/api/product/attr";
import { getSpuSaleAttrListApi, getSpuImgListApi } from "@/api/product/spu";
import { useCategoryStore } from "@/stores/category";
const emit = defineEmits(["setIsShow"]);
const spuStore = useSpuStore();
const confirmAddSku = async () => {
  await skuFormRef.value?.validate();
  await getSaveSkuInfoApi({
    ...skuFormData,
    skuAttrValueList: skuFormData.skuAttrValueList
      .filter(Boolean)
      .map((platformAttr) => {
        const [attrId, attrName, valueId, valueName] = (
          platformAttr as string
        ).split(":");
        return {
          valueId: +valueId,
          valueName: valueName,
          attrId: +attrId,
          attrName: attrName,
        };
      }),
    skuSaleAttrValueList: skuFormData.skuSaleAttrValueList
      .filter(Boolean)
      .map((saleAttr) => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = (
          saleAttr as string
        ).split(":");
        return {
          saleAttrId: +saleAttrId,
          saleAttrName: saleAttrName,
          saleAttrValueId: +saleAttrValueId,
          saleAttrValueName: saleAttrValueName,
        };
      }),
    spuId: spuStore.id as number,
    category3Id: categoryStore.category3Id as number,
  });
  ElMessage.success("添加成功！");
  setIsShow();
};
const skuImageListValidator = (
  rule: any,
  value: SkuImageList,
  callback: any
) => {
  if (!value.length) {
    callback(new Error("请添加一张或几张图片"));
  }
  if (value.some((img) => img.isDefault === "1")) {
    callback(new Error("请给选中的图片添加一个默认图片"));
  }
  callback();
};
// 表单三步
const skuFormRef = ref<FormInstance>();
const skuFormData = reactive<SkuCommon>({
  skuName: "",
  price: 0,
  weight: 0,
  skuDesc: "",
  skuAttrValueList: [
    //     {
    //       "attrId": 0,
    //       "attrName": "string",
    //       "id": 0,
    //       "skuId": 0,
    //       "valueId": 0,
    //       "valueName": "string"
    //     }
  ],
  skuSaleAttrValueList: [
    //     {
    //       "id": 0,
    //       "saleAttrId": 0,
    //       "saleAttrName": "string",
    //       "saleAttrValueId": 0,
    //       "saleAttrValueName": "string",
    //       "skuId": 0,
    //       "spuId": 0
    //     }
  ],

  skuImageList: [
    //     {
    //       "id": 0,
    //       "imgName": "string",
    //       "imgUrl": "string",
    //       "isDefault": "string",
    //       "skuId": 0,
    //       "spuImgId": 0
    //     }
  ],

  //   "spuId": 0,
  //   "tmId": 0,
  skuDefaultImg: "",
});
const skuFormRules = reactive<FormRules>({
  skuName: [{ required: true, message: "请输入SKU名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入规格描述", trigger: "blur" }],
  skuAttrValueList: [{ required: true, message: "请输入平台属性" }],
  skuSaleAttrValueList: [{ required: true, message: "请输入销售属性" }],
  skuImageList: [{ required: true, validator: skuImageListValidator }],
});
const platformAttrList = ref<AttrList>([]);
const saleAttrList = ref<SpuSaleAttrList>([]);
const imageList = ref<SkuImageList>([]);
const categoryStore = useCategoryStore();
// 获取平台属性
onMounted(async () => {
  const { category1Id, category2Id, category3Id } = categoryStore;
  platformAttrList.value = await getAttrListApi({
    category1Id: category1Id as number,
    category2Id: category2Id as number,
    category3Id: category3Id as number,
  });
});
// 获取销售属性
onMounted(async () => {
  saleAttrList.value = await getSpuSaleAttrListApi(spuStore.id as number);
});
// 获取图片
onMounted(async () => {
  const result = await getSpuImgListApi(spuStore.id as number);
  imageList.value = result.map((item) => {
    return { ...item, isDefault: "0" };
  });
});
// 选择复选框触发事件
const selectionChange = (val: SkuImageList) => {
  skuFormData.skuImageList = val;
};
const setDefault = (row: SkuImageItem) => {
  imageList.value.forEach((img) => (img.isDefault = "0"));
  row.isDefault = "1";
  skuFormData.skuDefaultImg = row.imgUrl;
  if (skuFormData.skuImageList.some((img) => img === row)) {
    skuFormRef.value?.clearValidate(["skuImageList"]);
  }
};

const setIsShow = () => {
  emit("setIsShow", 1);
};
</script>

<style scoped>
.sku-input-number,
.skuRow,
.skuSaleSelect,
.skuAttrSelect {
  width: 100%;
}
.el-col {
  border-radius: 4px;
}
.skuClassWrap {
  display: flex;
}
.addSkuForm:deep(.el-input__inner) {
  text-align: left;
}
.sku-select {
  margin-left: 10px;
  margin-bottom: 10px;
  flex: 1;
}
.sku-select-text {
  width: 100px;
  text-align: right;
}
</style>
